package edu.pitt.dbmi.odie.gapp.gwt.server.user;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gdata.client.http.AuthSubUtil;
import com.google.gdata.util.AuthenticationException;

import edu.pitt.dbmi.odie.gapp.gwt.server.navigator.ODIE_SelectionCacher;
import edu.pitt.dbmi.odie.gapp.gwt.server.util.gdata.ODIE_DocsServiceFetcher;

@SuppressWarnings("serial")
public class ODIE_SignOutServlet extends HttpServlet {

	private static final Logger log = Logger
			.getLogger(ODIE_SignOutServlet.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			
			ODIE_ServerSideLoginInfo serverSideLoginInfo = (ODIE_ServerSideLoginInfo) this
					.getServletContext().getAttribute(
							ODIE_ServerSideLoginInfo.class.getName());
			if (serverSideLoginInfo != null) {
				String revokeToken = serverSideLoginInfo
						.getAuthSubSessionToken();
				AuthSubUtil.revokeToken("http", "webodie.net", revokeToken,
						null);
				log.info("ODIE_SignOutServlet: Revoked token " + revokeToken);
				ODIE_DocsServiceFetcher.releaseDocsService(this);
				ODIE_SelectionCacher.releaseOdieSelectionCacher(this);
			}
			this
			.getServletContext().removeAttribute(
					ODIE_ServerSideLoginInfo.class.getName());

		} catch (AuthenticationException e) {
			log.info("ODIE_SignOutServlet fails with " + e.getMessage()) ;
		} catch (GeneralSecurityException e) {
			log.info("ODIE_SignOutServlet fails with " + e.getMessage()) ;
		}
		
		String reDirectUrl = ODIE_UserUtils.reDirectToOdieClient(req, resp) ;
		resp.sendRedirect(reDirectUrl) ;
	}
}
